package su.msk.jet.team01.chatik.server.commands;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import su.msk.jet.team01.chatik.server.data.Client;
import su.msk.jet.team01.chatik.server.data.DataManager;
import su.msk.jet.team01.chatik.server.db.DatabaseAdapter;
import su.msk.jet.team01.chatik.server.exception.ClientNotFoundException;
import su.msk.jet.team01.chatik.server.exception.InvalidArgumentException;

import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;

public class SendPrivateCommand extends Command {
	private static DatabaseAdapter database = DatabaseAdapter.get();

	private static Logger logger = LoggerFactory.getLogger(SendPrivateCommand.class);
	
	public SendPrivateCommand() {
		super("private", 2);
	}

	@Override
	public void execute(final Client client, final String[] args) {
		String destClientName = args[0];
		String message = args[1];
		Client destClient = null;

		if (client.getName().isEmpty()) {
			client.send("You should select nick to send messages. Use /name command.");
			return;
		}

		try {
			validateLength(message, MAX_MESSAGE_LENGTH);

			try {
				destClient = DataManager.findClient(destClientName);
			} catch (ClientNotFoundException e) {
				client.send(
						"Client with name \"%s\" can not be found online, send to offline.",
						destClientName);
			}

			int databaseClientId = DataManager.getDatabaseID(client.getName());
			int databaseDestId = DataManager.getDatabaseID(destClientName);
			logDatabaseMessage(databaseClientId, databaseDestId, message);

			if (destClient != null) {
				destClient.send("%s (private) %s: %s", client.getName(),
						destClientName, message);
			}
			client.send("%s (private) %s: %s", client.getName(),
					destClientName, message);
		} catch (InvalidArgumentException e) {
			client.send("Message is too long. Maximum message length is %d.",
					MAX_MESSAGE_LENGTH);
		} catch (Exception e) {
			client.send("Private message to \"%s\" sending failed.",
					destClientName);
			logger.error("Client " + client.getName()
					+ " failed to send private message to " + destClientName, e);
		}
	}

	private void logDatabaseMessage(final int from, final int to,
			final String message) {
		Calendar c = Calendar.getInstance();
		Date date = c.getTime();

		try {
			database.execute(
					"INSERT INTO messages (date, time, from_user_id, to_user_id, message) VALUES (?, ?, ?, ?, ?)",
					new java.sql.Date(date.getTime()),
					new java.sql.Time(date.getTime()), from, to, message);
		} catch(SQLException ex) {
			logger.error(ex.getMessage(), ex);
		}
	}
}